package com.acme.javaschool.sems.ionio.serialization.impl;

import com.acme.javaschool.sems.ionio.serialization.SensorData;
import com.acme.javaschool.sems.ionio.serialization.Serializer;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.*;

public class JsonSerializer implements Serializer<SensorData>{

    private final Gson gson = new Gson();

    @Override
    public void serialize(OutputStream outputStream, SensorData object) {
        try {
            JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(outputStream));
            gson.toJson(object, SensorData.class, jsonWriter);
            jsonWriter.flush();

        } catch (IOException e) { e.printStackTrace(); }

    }

    @Override
    public SensorData deserialize(InputStream inputStream) {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
            return gson.fromJson(reader, SensorData.class);
        } catch (Exception e) { e.printStackTrace(); }

        return null;
    }
}
